﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Resto.CostControl.Core.Domain.Query.SupplierModule;
using Enterprise.Framework.Core.Container;
using Resto.CostControl.Core.Facade.SupplierModule.DataTransferObject;
using Resto.CostControl.Core.Domain.Model;
using Resto.CostControl.Core.Domain.Query.MaterialModule;
using Resto.CostControl.Core.Enums;
using Enterprise.Framework.Frame.Architecture;

namespace Resto.CostControl.Core.Facade.SupplierModule.FacadeObject
{
    /// <summary>
    /// 原材料采购单FO
    /// </summary>
    public class MaterialPurchaseFO : IApplicationFacadeObject
    {
        #region 私有属性

        private MaterialPurchaseDQO _MaterialPurchaseDQO;
        private MaterialPurchaseDQO MaterialPurchaseDQO
        {
            get
            {
                if (_MaterialPurchaseDQO == null)
                    _MaterialPurchaseDQO = ObjectCreator.Create<MaterialPurchaseDQO>();

                return _MaterialPurchaseDQO;
            }
        }

        #endregion

        #region 公共方法

        public virtual void AddMaterialPurchase(MaterialPurchaseDTO contractDTO, MaterialPurchaseState state)
        {
            MaterialPurchase supplierContract = contractDTO.ToMaterialPurchase();
            supplierContract.UpdateState(state);

            supplierContract.Add();

            RestoCostDomainSession.CurrentSession.SaveChanges();

            contractDTO.ID = supplierContract.ID;
        }

        public virtual void UpdateMaterialPurchase(MaterialPurchaseDTO contractDTO, MaterialPurchaseState state)
        {
            MaterialPurchase supplierContract = MaterialPurchaseDQO.GetMaterialPurchase(contractDTO.ID);
            supplierContract.UpdateState(state);

            contractDTO.CopyToMaterialPurchase(supplierContract);

            supplierContract.Update();

            if (state == MaterialPurchaseState.Storage)
            { 
                //保存库存变更记录
                foreach (MaterialPurchaseItem item in supplierContract.Items)                
                    MaterialStorageHistory.CreateStorageHistory(item);
                
            }

            RestoCostDomainSession.CurrentSession.SaveChanges();

        }

        public virtual void DeleteMaterialPurchase(string id)
        {
            MaterialPurchase supplierContract = MaterialPurchaseDQO.GetMaterialPurchase(id);

            supplierContract.Delete();

            RestoCostDomainSession.CurrentSession.SaveChanges();

        }

        public virtual MaterialPurchaseDTO GetMaterialPurchaseDTO(string id)
        {
            MaterialPurchase supplierContract = MaterialPurchaseDQO.GetMaterialPurchase(id);

            return new MaterialPurchaseDTO(supplierContract);
        }

        #endregion

       
    }
}
